<template>
  <div class="roles">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card -->
    <el-card>
      <!-- 按钮  layout布局-->
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="rolesAddDialog = !rolesAddDialog">添加按钮</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <!-- 渲染一级菜单 -->
            <el-row
              v-for="(item,index) in scoped.row.children"
              :key="item.id"
              :style="{'border-bottom':'1px solid #eee','border-top':index===0?'1px solid #eee':''}"
            >
              <el-col :span="5">
                <el-tag closable @close="delroles(scoped.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级菜单 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item.children"
                  :key="item2.id"
                  :cc="index2"
                  :style="{'border-top':index2===0?'':'1px solid #eee'}"
                >
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="delroles(scoped.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级选项 -->
                  <el-col :span="19">
                    <el-tag
                      closable
                      v-for="(item3,inex3) in item2.children"
                      :key="item3.id"
                      :cc="inex3"
                      type="warning"
                      @close="delroles(scoped.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-search" @click="updateRoles(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="setRight(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加弹出框 -->
    <el-dialog title="提示" :visible.sync="rolesAddDialog" width="50%">
      <el-form
        :model="rolesForm"
        :rules="rolesRules"
        ref="rolesFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--  编辑弹出框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form :model="updateform" ref="updateref" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="updateform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="rightDialog" width="40%">
      <!-- 树形控件 -->
      <el-tree
        :props="treeProp"
        :data="treeList "
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRitht">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      updateform: {
        roleDesc: "",
        roleName: "",
        roleId: ""
      },
      rolesList: [],
      rolesAddDialog: false,
      dialogVisible: false,
      rightDialog: false,
      rolesForm: {
        roleName: "",
        roleDesc: ""
      },
      rolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      },
      // 获取权限列表的数组
      treeList: [],
      // 每个节点之间的关系
      treeProp: {
        // 展示节点的内容
        label: "authName",
        // 嵌套
        children: "children"
      },
      // 默认选中的三级权限
      defaultCheckedKeys: [],
      roleId: ""
    };
  },
  methods: {
    //   获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
    },
    //添加角色
    addRoles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.rolesForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色列表失败");
        }
        this.rolesAddDialog = !this.rolesAddDialog;
        this.getRolesList();
      });
    },
    // 删除
    async deleteRoles(id) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        return "clac";
      });
      console.log(result);
      if (result == "clac") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      }
      if (result == "confirm") {
        const { data: res } = await this.$http.delete(`roles/${id}`);
        this.$message.success("删除成功");
        this.getRolesList();
      }
    },
    // 根据id修改
    async updateRoles(id) {
      this.dialogVisible = !this.dialogVisible;
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.updateform = res.data;
    },
    // 确定修改
    update() {
      this.$refs.updateref.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `roles/${this.updateform.roleId}`,
          this.updateform
        );
        if (res.meta.status !== 200) return this.$message.error("获取数据失败");
        this.getRolesList();
        this.dialogVisible = false;
      });
    },
    
    // 分配权限 获取权限列表
    async setRight(role) {

      // 更改用户的id 提前存储
      this.roleId = role.id;
      const { data: res } = await this.$http.get(`rights/tree`);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.treeList = res.data;
      // console.log(this.treeList);
      const keys = [];

      this.getlifeId(role, keys);
      // console.log(keys)
      this.defaultCheckedKeys = keys;
      this.rightDialog = true;
    },
    // 递归获取角色三级权限
    getlifeId(node, keyArr) {
      if (!node.children) {
        return keyArr.push(node.id);
      }
      node.children.forEach(item => this.getlifeId(item, keyArr));
    },
    // 删除项
    async delroles(role, rightId) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      // console.log(result);
      // 校验
      if (result == "cancel") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      }
      if (result == "confirm") {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        );
        // console.log(role.id,rightId)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error("取消权限失败");
        this.$message.success("取消权限成功");
        role.children = res.data;
      }
    },
    // 点击确定分配权限
    async saveRitht() {
      const k1 = this.$refs.tree.getCheckedKeys();
      const k2 = this.$refs.tree.getHalfCheckedKeys();
      //  console.log(k1,k2)
      const str = [...k1, ...k2].join(",");
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: str
      });
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success("更新成功");
      this.getRolesList()
      this.rightDialog = false;
    }
  },

  created() {
    this.getRolesList();
  }
};
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 10px;
}
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin: 10px 5px;
}
</style>

